package zhoug.common.fileselector.selector.impl;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;

import zhoug.common.R;
import zhoug.common.content.FileType;
import zhoug.common.fileselector.beans.LocalMedia;
import zhoug.common.fileselector.selector.ui.FileSelectorActivity;
import zhoug.common.utils.FileUtils;
import zhoug.logging.Logger;
import zhoug.common.utils.UriUtils;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;

import androidx.activity.ComponentActivity;
import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultCaller;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.DefaultLifecycleObserver;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleOwner;

/**
 * 文件选择器,使用自定义的FileChooserActivity选择文件
 *
 * @Author HK-LJJ
 * @Date 2020/1/8
 * @Description
 */
class FileSelectorImpl extends AbsFileSelector {
    private static final String TAG = ">>>FileChooserImpl";
    private boolean mIsSystemIntent = false;//标记是调用系统还是自定义文件选择
    private ActivityResultLauncher<Intent> mChooserLauncher;

    FileSelectorImpl(ComponentActivity activity) {
        super(activity);
        register(activity.getLifecycle(), activity);
    }

    FileSelectorImpl(Fragment fragment) {
        super(fragment);
        register(fragment.getLifecycle(), fragment);
    }

    private Context getContext() {
        if (mFragment != null) {
            return mFragment.getContext();
        } else {
            return mActivity;
        }
    }

    private void register(Lifecycle lifecycle, ActivityResultCaller activityResultCaller) {
        lifecycle.addObserver(new DefaultLifecycleObserver() {
            @Override
            public void onCreate(@NonNull LifecycleOwner owner) {
                mChooserLauncher = activityResultCaller.registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
                    @Override
                    public void onActivityResult(ActivityResult result) {
                        onResult(result);
                    }
                });
            }

            @Override
            public void onDestroy(@NonNull LifecycleOwner owner) {
                if (mChooserLauncher != null) {
                    mChooserLauncher.unregister();
                    mChooserLauncher = null;
                }
            }
        });
    }

    @Override
    public void show() {
        if(mChooserLauncher==null){
            Logger.e(TAG, "show:mChooserLauncher is null");
            return;
        }
        int fileType = config.fileType;
        Intent intent = null;
        /*if (fileType == FileType.WORD) {
            //word
            intent = IntentUtils.getContentIntent("application/msword");
        } else if (fileType == FileType.EXCEL) {
            //excel
            intent = IntentUtils.getContentIntent("application/vnd.ms-excel");
        } else if (fileType == FileType.PDF) {
            //pdf
            intent = IntentUtils.getContentIntent("application/pdf");
        } else if (fileType == FileType.TXT) {
            //txt
            intent = IntentUtils.getContentIntent("text/plain");
        }*/
        if (intent != null) {
            //文件系统
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//授予临时权限别忘了
            intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, !config.singleModel);
            mIsSystemIntent = true;
        } else {
            intent = FileSelectorActivity.getNavigationIntent(mActivity, config);
            mIsSystemIntent = false;
        }
        ComponentName componentName = intent.resolveActivity(getContext().getPackageManager());
        if (componentName == null) {
            Logger.e(TAG, "No Activity found to handle Intent:" + intent);
            return;
        }

       /* if (mFragment != null) {
            mFragment.startActivityForResult(intent, REQUEST_CODE);
        } else {
            mActivity.startActivityForResult(intent, REQUEST_CODE);
        }*/
        mChooserLauncher.launch(intent);
        //动画
        mActivity.overridePendingTransition(R.anim.common_alpha_activity_int, R.anim.common_alpha_activity_out);

    }


    private void onResult(ActivityResult activityResult) {
        if (activityResult != null && activityResult.getResultCode() == Activity.RESULT_OK &&  activityResult.getData()!=null) {
            Intent data = activityResult.getData();
            if (!mIsSystemIntent) {
                Serializable result = data.getSerializableExtra(FileSelectorActivity.EXTRA_RESULT_MEDIA);
                if (mOnFileChooseListener != null) {
                    if (result == null) {
                        mOnFileChooseListener.onResult(new ArrayList<>());
                    } else {
                        ArrayList<LocalMedia> localMedias = (ArrayList<LocalMedia>) result;
                        mOnFileChooseListener.onResult(localMedias);
                    }
                }
            } else {
                Uri uri = data.getData();
                String path = UriUtils.getPathFromUri(getContext(), uri);
                Logger.d(TAG, "onActivityResult:path:" + path);
                if (mOnFileChooseListener != null) {
                    ArrayList<LocalMedia> result = new ArrayList<>();
                    if (path != null) {
                        LocalMedia localMedia = new LocalMedia();
                        localMedia.setPath(path);
                        localMedia.setFileType(FileType.getType(path));
                        localMedia.setName(FileUtils.getNameWithSuffix(path));
                        localMedia.setSize(new File(path).length());
                        result.add(localMedia);
                    }
                    mOnFileChooseListener.onResult(result);
                }

            }

        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK && data != null) {
            if (!mIsSystemIntent) {
                Serializable result = data.getSerializableExtra(FileSelectorActivity.EXTRA_RESULT_MEDIA);
                if (mOnFileChooseListener != null) {
                    if (result == null) {
                        mOnFileChooseListener.onResult(new ArrayList<>());
                    } else {
                        ArrayList<LocalMedia> localMedias = (ArrayList<LocalMedia>) result;
                        mOnFileChooseListener.onResult(localMedias);
                    }
                }
            } else {
                Uri uri = data.getData();
                String path = UriUtils.getPathFromUri(getContext(), uri);
                Logger.d(TAG, "onActivityResult:path:" + path);
                if (mOnFileChooseListener != null) {
                    ArrayList<LocalMedia> result = new ArrayList<>();
                    if (path != null) {
                        LocalMedia localMedia = new LocalMedia();
                        localMedia.setPath(path);
                        localMedia.setFileType(FileType.getType(path));
                        localMedia.setName(FileUtils.getNameWithSuffix(path));
                        localMedia.setSize(new File(path).length());
                        result.add(localMedia);
                    }
                    mOnFileChooseListener.onResult(result);
                }
            }
        }
    }


}
